package com.shxc.smarttrade.old.foreignfragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.quotation.old.AllQuotationActivity;
import com.shxc.smarttrade.old.activity.RechargeActivity;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.iview.IViewStockChart;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.StockChartPresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CountClass;
import com.shxc.smarttrade.old.utils.Logger;
import com.shxc.smarttrade.old.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by jcdev1 on 2017/5/25.
 */

public class MarketPriceFragment extends Fragment implements IViewStockChart {
    @BindView(R.id.have_ll_buy_rise)
    LinearLayout haveLLBuyRise;
    @BindView(R.id.have_ll_buy_fall)
    LinearLayout haveLLBuyFall;
    @BindView(R.id.have_tv_buy_rise)
    TextView haveTVBuyRise;
    @BindView(R.id.have_tv_buy_fall)
    TextView haveTVBuyFall;

    @BindView(R.id.tv_hand_times)
    EditText tvHandTimes;
    @BindView(R.id.tv_price)
    EditText tvPrice;
    @BindView(R.id.tv_price_remind)
    TextView tvPriceRemind;

    @BindView(R.id.tv_stop_loss_range)
    TextView tvStopLossRange;
    @BindView(R.id.tv_stop_loss)
    EditText tvStopLoss;
    @BindView(R.id.tv_stop_profit_range)
    TextView tvStopProfitRange;
    @BindView(R.id.tv_stop_profit)
    EditText tvStopProfit;
    @BindView(R.id.tv_margin)
    TextView tvMargin;
    @BindView(R.id.tv_loss)
    TextView tvLoss;
    @BindView(R.id.tv_profit)
    TextView tvProfit;

    @BindView(R.id.iv_stop_loss_sub)
    ImageView ivStopLossSub;
    @BindView(R.id.iv_stop_loss_add)
    ImageView ivStopLossAdd;
    @BindView(R.id.iv_stop_profit_sub)
    ImageView ivStopProfitSub;
    @BindView(R.id.iv_stop_profit_add)
    ImageView ivStopProfitAdd;
    @BindView(R.id.ll_pending_price)
    LinearLayout llPendingPrice;


    private View rootView;
    public int whatBuyRiseOrFall = 0;//默认买入
    private double minVolume = 0;//手数最小值，以及手数每次增减量
    private double volume;//购买手数，待提交参数
    private double stopLevel;//步长，为防止轻易平仓而设
    private double pendingPrice = 0;//挂单价格，待提交参数
    private double pendingTotal;//挂单价格累积量
    private double priceVar;//所有价格的变化量
    private double stopLossMax;//止损最值
    private double stopProfitMax;//止盈最值
    private double pendingLossMax;//挂单，买入时最值1
    private double pendingProfitMax;//挂单，买入时最值2
    private double pendingPriceMiddle = 0;//挂单价过度值

    private double tp;//止盈价，待提交参数
    private double sl;//止损价，待提交参数
    private double stopLossTotal;//止损价格累积量
    private double stopProfitTotal;//止盈价格累积量

    private int type;//当前项目类型
    private double marginBase;//占用保证金计算基数
    private double ask;//实时买价
    private double bid;//实时卖价
    private double market;//实时市场价
    //    private double price;//实时(ask+bid)/2
    private boolean marginChange = false;//保证金是否要转化成美元
    private boolean profitChange = false;//盈亏是否要转化成美元
    private boolean profitUSDPrex = false;//盈亏是否已美元为基础货币
    private boolean usdprex = false;//保证金是否已美元为基础货币
    private int contracSize;//合约数
    private double accAmt;//账户余额
    private int digits;//位数
    private String buyMax;//最大购买手数等连接的字符串
    private double handMax;//最大购买手数
    private int tag = 0;//实时数据中的标记，为了只执行一次
    private StockChartPresenter presenter = new StockChartPresenter(this);
    private String symbol;
    private String symbolCn;
    private PopupWindow popupWindow;
    //    private StockChartUpgradeActivity activity = (StockChartUpgradeActivity) getActivity();
    private MyProgressDialog dialog;
    private String[] symbols = null;//保证金和盈亏计算所需要的不同品种英文名称
    private double[] askBidOne = null;
    private double[] askBidTwo = null;
    private double[] askBidThree = null;
    private Handler handler = new Handler();
    private Runnable runnable;
    private int showTime = 5000;
    private boolean isFinishActivity = false;//是否在popupWindow消失时关闭Activity
    private double marginAll;//保证金总数
    private boolean quickOrderStatus = false;//是否开启快捷开仓


    private AllQuotationActivity allQuotationActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_market_and_pending_control, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, rootView);
        allQuotationActivity = (AllQuotationActivity) getActivity();
        Intent intent = getActivity().getIntent();
        symbol = intent.getStringExtra("symbol");
        symbolCn = intent.getStringExtra("symbolCn");
        digits = intent.getIntExtra("digits", -1);
        quickOrderStatus = SpUtils.getBoolean(getActivity(), "quickOrderStatus", false);

        llPendingPrice.setVisibility(View.GONE);
        initListener();
        initDatas();
        return rootView;
    }

    private void initDatas() {
        setSymbolCalInfoDatas(allQuotationActivity.symbolInfo);
    }

    /**
     * 四个编辑框的监听器
     */
    private void initListener() {
        tvPrice.addTextChangedListener(new EditTextListener(0));
        tvHandTimes.addTextChangedListener(new EditTextListener(1));
        tvStopLoss.addTextChangedListener(new EditTextListener(2));
        tvStopProfit.addTextChangedListener(new EditTextListener(3));
//        tvPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                if (!hasFocus) {
//                    InputMethodManager im = (InputMethodManager) getActivity().getSystemService(getContext().INPUT_METHOD_SERVICE);
//                    im.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                }
//            }
//        });

//        ((StockChartUpgradeActivity) getActivity()).llAll.setOnSoftKeybordStatusListener(new CommonAutoRelativeLayout.softKeybordStatusListener() {
//            @Override
//            public void softKeybordStatus(boolean status) {
//
//                if (status) {
//                    tvPrice.setCursorVisible(true);
//                    tvHandTimes.setCursorVisible(true);
//                    tvStopLoss.setCursorVisible(true);
//                    tvStopProfit.setCursorVisible(true);
//                } else {
//                    tvPrice.setCursorVisible(false);
//                    tvHandTimes.setCursorVisible(false);
//                    tvStopLoss.setCursorVisible(false);
//                    tvStopProfit.setCursorVisible(false);
//                }
//            }
//        });
    }


    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        //提交挂单信息
        String ev = event.getTagOne();
        if (ev.equals(EventContents.ALL_QUOTATION_ACTIVITY_ONE)) {//买涨
            if (handMax != 0) {
                if (quickOrderStatus)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), 0, (float) volume, tp, sl);
                else
                    submitTraderOpenData(0);
            } else {
                setPopupUnderMargin();
            }

        } else if (ev.equals(EventContents.ALL_QUOTATION_ACTIVITY_TWO)) {//买跌
            if (handMax != 0) {
                if (quickOrderStatus)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), 1, (float) volume, tp, sl);
                else
                    submitTraderOpenData(1);
            } else {
                setPopupUnderMargin();
            }

        }
    }

    /**
     * 开仓前提示
     */
    private void submitTraderOpenData(final int where) {
        View view = View.inflate(getContext(), R.layout.pop_style_sure_orders, null);
        TextView tvItemName = (TextView) view.findViewById(R.id.tv_item_name);
        TextView tvBuyRise = (TextView) view.findViewById(R.id.tv_buy_rise);
        TextView tvHandTimes = (TextView) view.findViewById(R.id.tv_hand_times);
        TextView tvStopProfit = (TextView) view.findViewById(R.id.tv_stop_profit);
        TextView tvStopLoss = (TextView) view.findViewById(R.id.tv_stop_loss);
        TextView btnSure = (TextView) view.findViewById(R.id.btn_go_order);
        TextView btnCancle = (TextView) view.findViewById(R.id.btn_cancel);
        TextView tvBuyStatus = (TextView) view.findViewById(R.id.tv_buy_status);
        TextView tvHandsAndName = (TextView) view.findViewById(R.id.tv_hands_money_name);
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.e("tp:", tp + "  sl:" + sl);
                if (where == 0)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), 0, (float) volume, tp, sl);
                else if (where == 1)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), 1, (float) volume, tp, sl);
                else if (where == 2)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbol, SpUtils.getInt(getContext(), "userId"), whatBuyRiseOrFall, (float) volume, tp, sl);
                popupWindow.dismiss();
            }
        });
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvItemName.setText(symbolCn + " " + symbol);
        switch (where) {
            case 0:
                tvBuyRise.setText("买涨：" + BaseUtils.getDigitsData(ask, digits));
                tvBuyStatus.setText("买涨");
                tvBuyStatus.setBackgroundResource(R.drawable.blue_text_bg);
                break;
            case 1:
                tvBuyRise.setText("买跌：" + BaseUtils.getDigitsData(bid, digits));
                tvBuyStatus.setText("买跌");
                tvBuyStatus.setBackgroundResource(R.drawable.orange_text_bg);
                break;
            case 2:
                if (whatBuyRiseOrFall == 0) {
                    tvBuyRise.setText("买涨：" + BaseUtils.getDigitsData(ask, digits));
                    tvBuyStatus.setText("买涨");
                    tvBuyStatus.setBackgroundResource(R.drawable.yellow_text_bg);
                } else {
                    tvBuyRise.setText("买跌：" + BaseUtils.getDigitsData(bid, digits));
                    tvBuyStatus.setText("买跌");
                    tvBuyStatus.setBackgroundResource(R.drawable.green_text_bg);

                }
                break;
        }

        tvHandTimes.setText("占用：" + "$" + marginAll);
        tvHandsAndName.setText(" " + volume + "手 " + symbolCn);
        if (tp == 0) {
            tvStopProfit.setText("止盈：未设置");
        } else {
            tvStopProfit.setText("止盈：" + BaseUtils.getDigitsData(tp, digits));
        }
        if (sl == 0) {
            tvStopLoss.setText("止损：未设置");
        } else {
            tvStopLoss.setText("止损：" + BaseUtils.getDigitsData(sl, digits));

        }
        isFinishActivity = false;
        showPopupWindow(view);
    }

    /**
     * 弹出资金不足提示框
     */
    private void setPopupUnderMargin() {
        View view = View.inflate(getContext(), R.layout.dialog_under_margin, null);
        TextView btnGoRecharge = (TextView) view.findViewById(R.id.btn_go_recharge);
        TextView btnEnsure = (TextView) view.findViewById(R.id.btn_ensure);
        btnGoRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), RechargeActivity.class));
                popupWindow.dismiss();
            }
        });
        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        isFinishActivity = false;
        showPopupWindow(view);
    }

    /**
     * 接收由Activity提供的实时数据
     *
     * @param quoteBeen
     */
    public void setRealTimeDatas(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        int quoteBeenSize = quoteBeen.size();

        if (quoteBeen != null && quoteBeenSize > 0) {

            if (haveTVBuyRise == null) return;

            for (int i = 0; i < quoteBeenSize; i++) {
                String curSymbol = quoteBeen.get(i).getSymbol();
                if (curSymbol.equals(symbol)) {
                    ask = quoteBeen.get(i).getAsk();
                    bid = quoteBeen.get(i).getBid();
                    askBidOne = new double[]{ask, bid};
                }
                if (symbols != null && curSymbol.equals(symbols[1])) {
                    askBidTwo = new double[]{quoteBeen.get(i).getAsk(), quoteBeen.get(i).getBid()};
                }
                if (symbols != null && curSymbol.equals(symbols[2])) {
//                    Log.e("current22", quoteBeen.get(i).getSymbol() + " ask:" + quoteBeen.get(i).getAsk() + "  bid:" + quoteBeen.get(i).getBid());
                    askBidThree = new double[]{quoteBeen.get(i).getAsk(), quoteBeen.get(i).getBid()};
                }
            }

//            ask = quoteBeen.get(0).getAsk();
//            bid = quoteBeen.get(0).getBid();
            market = quoteBeen.get(0).getMarket();
//            price = Arith.div(Arith.add(ask, bid), 2, digits);


            haveTVBuyRise.setText(BaseUtils.getDigitsData(ask, digits));
            haveTVBuyFall.setText(BaseUtils.getDigitsData(bid, digits));
            if (whatBuyRiseOrFall == 0) {//买入
                double marker = Arith.add(market, Arith.div(20, Math.pow(10, digits)));
                pendingLossMax = Arith.sub(ask, stopLevel);
                pendingProfitMax = Arith.add(ask, stopLevel);
                if (pendingPrice != 0) {
                    stopLossMax = Arith.sub(pendingPrice, stopLevel);
                    stopProfitMax = Arith.add(pendingPrice, stopLevel);
                } else {
                    stopLossMax = Arith.sub(bid, stopLevel);
                    stopProfitMax = Arith.add(bid, stopLevel);
                }

                tvPriceRemind.setText("价格(≤" + BaseUtils.getDigitsData(pendingLossMax, digits) + "或≥" + BaseUtils.getDigitsData(pendingProfitMax, digits) + ")");
                tvStopLossRange.setText("≤" + BaseUtils.getDigitsData(stopLossMax, digits));
                tvStopProfitRange.setText("≥" + BaseUtils.getDigitsData(stopProfitMax, digits));

            } else {//卖出
                pendingLossMax = Arith.add(bid, stopLevel);
                pendingProfitMax = Arith.sub(bid, stopLevel);
                if (pendingPrice != 0) {
                    stopLossMax = Arith.add(pendingPrice, stopLevel);
                    stopProfitMax = Arith.sub(pendingPrice, stopLevel);

                } else {
                    stopLossMax = Arith.add(ask, stopLevel);
                    stopProfitMax = Arith.sub(ask, stopLevel);
                }

                tvPriceRemind.setText("价格(≤" + BaseUtils.getDigitsData(pendingProfitMax, digits) + "或≥" + BaseUtils.getDigitsData(pendingLossMax, digits) + ")");
                tvStopLossRange.setText("≥" + BaseUtils.getDigitsData(stopLossMax, digits));
                tvStopProfitRange.setText("≤" + BaseUtils.getDigitsData(stopProfitMax, digits));
            }
//            if (tag == 0) {
            double margin2 = CountClass.getMargin(type, volume, askBidOne, askBidTwo, whatBuyRiseOrFall, marginBase, marginChange, usdprex);
            if (margin2 == -1) return;
            if (accAmt > margin2) {
                double accAmt2 = Arith.round(Arith.mul(accAmt, 0.8), 2);
                handMax = Arith.div2(Arith.mul(accAmt2, volume), margin2, 2);
                handMax = Arith.div(handMax, minVolume, 0);//处理最小手数不定的情况
                handMax = Arith.mul(handMax, minVolume);
                buyMax = "|最大可买:" + handMax + "手";
            } else {
                buyMax = "|最大可买:" + 0 + "手";
            }
            tvMargin.setText("需资金:$" + margin2 + buyMax);
            marginAll = margin2;
//            }

        }
    }

    /**
     * 品种保证金及止盈止损数据
     *
     * @param symbolInfo
     */
    public void setSymbolCalInfoDatas(SymbolInfo symbolInfo) {
        if (symbolInfo != null) {
            minVolume = symbolInfo.getMinVolume();
            volume = symbolInfo.getMinVolume();
            if (tvHandTimes == null) return;
            tvHandTimes.setText(minVolume + "");
            symbols = new String[]{symbol, symbolInfo.getMarginCalCurrency(), symbolInfo.getProfitCalCurrency()};
            double stopLe = symbolInfo.getStopsLevel();
            digits = symbolInfo.getDigits();
            stopLevel = Arith.div(stopLe, Math.pow(10, digits), digits);
            priceVar = Arith.div(1, Math.pow(10, digits));

            type = symbolInfo.getType();
            marginBase = symbolInfo.getMarginBase();
            marginChange = symbolInfo.isMarginChange();
            profitChange = symbolInfo.isProfitChange();
            profitUSDPrex = symbolInfo.isProfitUSDPrex();
            usdprex = symbolInfo.isUsdprex();
            contracSize = symbolInfo.getContractSize();
            accAmt = symbolInfo.getAccAmt();
        }
    }


    /**
     * 选择买入
     */
    @OnClick(R.id.have_ll_buy_rise)
    public void haveLLBuyRise() {
        resetSomeVar();
        haveLLBuyRise.setBackgroundResource(R.mipmap.bg_red_checked);
        haveLLBuyFall.setBackgroundResource(R.mipmap.bg_no_check);
        whatBuyRiseOrFall = 0;
        allQuotationActivity.setBtnTradeTextAndColor(0);
    }

    /**
     * 选择卖出
     */
    @OnClick(R.id.have_ll_buy_fall)
    public void haveLLBuyFall() {
        resetSomeVar();
        haveLLBuyRise.setBackgroundResource(R.mipmap.bg_no_check);
        haveLLBuyFall.setBackgroundResource(R.mipmap.bg_green_checked);
        whatBuyRiseOrFall = 1;
        allQuotationActivity.setBtnTradeTextAndColor(1);
    }

    /**
     * 当更改买入状态时重置一些变量
     */
    private void resetSomeVar() {
        tvLoss.setText("");
        tvProfit.setText("");
        tvPrice.setText("");
        pendingTotal = 0;
        stopLossTotal = 0;
        stopProfitTotal = 0;
        pendingPrice = 0;
    }


    /**
     * 价格 减
     */
    @OnClick(R.id.iv_price_sub)
    public void ivPriceSub() {
        pendingTotal = Arith.sub(pendingTotal, priceVar);
        if (whatBuyRiseOrFall == 0) {
            if (pendingPriceMiddle <= pendingLossMax || pendingPriceMiddle == 0) {
                pendingPriceMiddle = Arith.add(pendingLossMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle <= pendingLossMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else if (pendingPriceMiddle >= pendingProfitMax) {
                pendingPriceMiddle = Arith.add(pendingProfitMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle >= pendingProfitMax) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else {
                pendingPriceMiddle = Arith.add(pendingLossMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle <= pendingLossMax || pendingPriceMiddle >= pendingProfitMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            }
        } else {
            if (pendingPriceMiddle <= pendingProfitMax || pendingPriceMiddle == 0) {
                pendingPriceMiddle = Arith.add(pendingProfitMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle <= pendingProfitMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else if (pendingPriceMiddle >= pendingLossMax) {
                pendingPriceMiddle = Arith.add(pendingLossMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle >= pendingLossMax) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else {
                pendingPriceMiddle = Arith.add(pendingProfitMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle <= pendingProfitMax || pendingPriceMiddle >= pendingLossMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            }

        }
    }

    /**
     * 价格 加
     */
    @OnClick(R.id.iv_price_add)
    public void ivPriceAdd() {
        pendingTotal = Arith.add(pendingTotal, priceVar);
        if (whatBuyRiseOrFall == 0) {

            if (pendingPriceMiddle >= pendingProfitMax || pendingPriceMiddle == 0) {
                pendingPriceMiddle = Arith.add(pendingProfitMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle >= pendingProfitMax) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else if (pendingPriceMiddle <= pendingLossMax) {
                pendingPriceMiddle = Arith.add(pendingLossMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle <= pendingLossMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else {
                pendingPriceMiddle = Arith.add(pendingProfitMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle >= pendingProfitMax || pendingPriceMiddle <= pendingLossMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }


            }
        } else {
            if (pendingPriceMiddle >= pendingLossMax || pendingPriceMiddle == 0) {
                pendingPriceMiddle = Arith.add(pendingLossMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle >= pendingLossMax) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else if (pendingPriceMiddle <= pendingProfitMax) {
                pendingPriceMiddle = Arith.add(pendingProfitMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));
                if (pendingPriceMiddle <= pendingProfitMax && pendingPriceMiddle > 0) {
                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            } else {
                pendingPriceMiddle = Arith.add(pendingLossMax, pendingTotal);
                tvPrice.setText(BaseUtils.getDigitsData(pendingPriceMiddle, digits));

                if (pendingPriceMiddle >= pendingLossMax || pendingPriceMiddle <= pendingProfitMax && pendingPriceMiddle > 0) {

                    pendingPrice = pendingPriceMiddle;
                } else {
                    showMyToast("价格不在范围内");
                    pendingPrice = 0;
                }
            }
        }
    }

    /**
     * 手数 减
     */
    @OnClick(R.id.iv_hand_times_sub)
    public void iVHandTimesSub() {
        if (volume > minVolume) {
            volume = Arith.sub(volume, minVolume);
            tvHandTimes.setText(volume + "");
            double margin2 = CountClass.getMargin(type, volume, askBidOne, askBidTwo, whatBuyRiseOrFall, marginBase, marginChange, usdprex);
            if (margin2 == -1) return;
            tvMargin.setText("需资金：" + margin2 + buyMax);
            marginAll = margin2;
        }
    }

    /**
     * 手数 加
     */
    @OnClick(R.id.iv_hand_times_add)
    public void setIvHandTimesAdd() {
        if (volume < handMax) {
            volume = Arith.add(volume, minVolume);
            tvHandTimes.setText(volume + "");
            double margin2 = CountClass.getMargin(type, volume, askBidOne, askBidTwo, whatBuyRiseOrFall, marginBase, marginChange, usdprex);
            if (margin2 == -1) return;
            tvMargin.setText("需资金：" + margin2 + buyMax);
            marginAll = margin2;
        }

    }

    /**
     * 设置止损止盈
     */
    @OnClick({R.id.iv_stop_loss_sub, R.id.iv_stop_loss_add, R.id.iv_stop_profit_sub, R.id.iv_stop_profit_add})
    public void setSLorTP(View view) {
        switch (view.getId()) {
            case R.id.iv_stop_loss_sub:
                setMySL(0);
                break;
            case R.id.iv_stop_loss_add:
                setMySL(1);
                break;
            case R.id.iv_stop_profit_sub:
                setMyTP(0);
                break;
            case R.id.iv_stop_profit_add:
                setMyTP(1);
                break;
        }
    }

    /**
     * 设置止损
     *
     * @param tagSL
     */
    private void setMySL(int tagSL) {
        if (tagSL == 0)
            stopLossTotal = Arith.sub(stopLossTotal, priceVar);
        else
            stopLossTotal = Arith.add(stopLossTotal, priceVar);

        double slcal = Arith.add(stopLossMax, stopLossTotal);
        tvStopLoss.setText(BaseUtils.getDigitsData(slcal, digits));
        sl = slcal;

        if (whatBuyRiseOrFall == 0) {//买入
            if (slcal <= stopLossMax && slcal > 0) {
//                sl = slcal;
                double profit;
                profit = getMyProfit(sl, 0, pendingPrice);
                if (profit == -1) return;
                tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvLoss.setText("止损不在范围内");
//                sl = 0;
            }
        } else {//卖出
            if (slcal >= stopLossMax) {
//                sl = slcal;
                double profit;
                profit = getMyProfit(sl, 1, pendingPrice);
                if (profit == -1) return;
                tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvLoss.setText("止损不在范围内");
//                sl = 0;
            }

        }
    }

    /**
     * 设置止盈
     *
     * @param tagTP
     */
    private void setMyTP(int tagTP) {
        if (tagTP == 0)
            stopProfitTotal = Arith.sub(stopProfitTotal, priceVar);
        else
            stopProfitTotal = Arith.add(stopProfitTotal, priceVar);

        double tpcal = Arith.add(stopProfitMax, stopProfitTotal);
        tvStopProfit.setText(BaseUtils.getDigitsData(tpcal, digits));
        tp = tpcal;
        if (whatBuyRiseOrFall == 0) {
            if (tpcal >= stopProfitMax) {
//                tp = tpcal;
                double profit;
                profit = getMyProfit(tp, 0, pendingPrice);
                if (profit == -1) return;
                tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvProfit.setText("止盈不在范围内");
//                tp = 0;
            }
        } else {
            if (tpcal <= stopProfitMax && tpcal > 0) {
//                tp = tpcal;
                double profit;
                profit = getMyProfit(tp, 1, pendingPrice);
                if (profit == -1) return;
                tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
            } else {
                tvProfit.setText("止盈不在范围内");
//                tp = 0;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showDialog() {
        dialog = new MyProgressDialog(getContext());
        dialog.setCancelable(false);
        dialog.show();

    }

    @Override
    public void dismissDialog() {
        if (dialog != null)
            dialog.dismiss();
    }

    @Override
    public void showMyToast(String str) {
        BaseUtils.showToast(str, getActivity());
//        ((StockChartUpgradeActivity) getActivity()).showToast(str);
    }

    @Override
    public void setSymbolCalInfoData(SymbolInfo symbolInfo) {

    }

    @Override
    public void setTradeOpenData(OpenTrader openTrader) {
        setPopupTraderOpenSuccess(openTrader);
    }

    /**
     * 挂单成功后返回值
     *
     * @param pendingOrder
     */
    @Override
    public void setPendingOrderData(PendingOrder pendingOrder) {

        showTime = 5000;
        View view = View.inflate(getContext(), R.layout.pop_buy_result, null);//pop_style_order_success
        TextView tvBuyResult = (TextView) view.findViewById(R.id.tv_buy_result);
        TextView tvBuyDetail = (TextView) view.findViewById(R.id.tv_buy_detail);
        LinearLayout llAll = (LinearLayout) view.findViewById(R.id.ll_all);
        tvBuyResult.setText("已成功 挂单");
        String detail = " " + symbolCn + " " + pendingOrder.getVolume() + "手，挂单价格 " + BaseUtils.getDigitsData(pendingOrder.getPendingPrice(), digits);
        if (pendingOrder.getCmd() == 0) {
            detail = "买入" + detail;
            llAll.setBackgroundResource(R.drawable.blue_text_bg);
        } else if (pendingOrder.getCmd() == 1) {
            detail = "卖出" + detail;
            llAll.setBackgroundResource(R.drawable.yellow_text_bg);
        } else if (pendingOrder.getCmd() == 2) {
            detail = "买入限价" + detail;
            llAll.setBackgroundResource(R.drawable.blue_text_bg);

        } else if (pendingOrder.getCmd() == 3) {
            detail = "卖出限价" + detail;
            llAll.setBackgroundResource(R.drawable.yellow_text_bg);

        } else if (pendingOrder.getCmd() == 4) {
            detail = "买入止损" + detail;
            llAll.setBackgroundResource(R.drawable.blue_text_bg);

        } else if (pendingOrder.getCmd() == 5) {
            detail = "卖出止损" + detail;
            llAll.setBackgroundResource(R.drawable.yellow_text_bg);
        }
        tvBuyDetail.setText(detail);

        EventBus.getDefault().post(new EventDatas(EventContents.PENDING_CONTROL_FINISH_PENDING, null));
        isFinishActivity = true;
        showPopupWindow(view);
        runnable = new Runnable() {
            @Override
            public void run() {
                showTime -= 1000;
                if (showTime == 0) {
                    handler.removeCallbacks(runnable);
                    popupWindow.dismiss();
                    getActivity().finish();

                } else
                    handler.postDelayed(runnable, 1000);
            }
        };
        handler.post(runnable);


    }

    @Override
    public void setSymbolPrice(SymbolPrice symbolPrice) {

    }

    /**
     * 显示操作对话框
     *
     * @param mainView
     */
    public void showPopupWindow(View mainView) {
        popupWindow = new PopupWindow(mainView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.AnimationBottonAndTop);
        popupWindow.showAtLocation(View.inflate(getContext(), R.layout.activity_stock_chart, null), Gravity.BOTTOM, 0, 0);
        setBackgroundAlpha(0.7f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
                if (runnable != null && handler != null) {
                    handler.removeCallbacks(runnable);
                }
                if (isFinishActivity)
                    getActivity().finish();
            }
        });
    }

    /**
     * 设置popupwindow背景色
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

    /**
     * who: 0：价格 1：手数 2：止损 3：止盈
     */
    class EditTextListener implements TextWatcher {
        int who;

        public EditTextListener(int who) {
            this.who = who;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //限制最大值和最小值
            String text = s.toString();
            int dotIndex = text.indexOf(".");
            int textLength = text.length();

            if (dotIndex == 0) {
                return;
            }
            if (textLength - 1 == dotIndex) {
                text = text + "00";
            }
            switch (who) {
                case 0:
                    if (textLength - dotIndex > digits + 1 && dotIndex != -1) {
                        text = text.substring(0, dotIndex + digits + 1);
                    }
                    double pendingPri = Double.parseDouble(text);
                    if (whatBuyRiseOrFall == 0) {
                        if (pendingPri >= pendingProfitMax) {
                            pendingPrice = pendingPri;
                            pendingTotal = Arith.sub(pendingPri, pendingProfitMax);
                        } else if (pendingPri <= pendingLossMax) {
                            pendingPrice = pendingPri;
                            pendingTotal = Arith.sub(pendingPri, pendingLossMax);
                        } else {
                            pendingPrice = 0;
                        }
                    } else {
                        if (pendingPri >= pendingLossMax) {
                            pendingPrice = pendingPri;
                            pendingTotal = Arith.sub(pendingPri, pendingLossMax);

                        } else if (pendingPri <= pendingProfitMax) {
                            pendingPrice = pendingPri;
                            pendingTotal = Arith.sub(pendingPri, pendingProfitMax);
                        } else {
                            pendingPrice = 0;
                        }
                    }

                    break;
                case 1:
                    if (textLength - dotIndex > 3 && dotIndex != -1) {
                        text = text.substring(0, dotIndex + 3);
                    }
                    double handtimes = Double.parseDouble(text);
                    if (handtimes < minVolume) {
                        volume = minVolume;
                        return;
                    }
                    if (handtimes > handMax) {
                        if (handMax == 0)
                            volume = minVolume;
                        else
                            volume = handMax;
                        return;
                    }
                    volume = handtimes;
                    break;
                case 2:
                    if (textLength - dotIndex > digits + 1 && dotIndex != -1) {
                        text = text.substring(0, dotIndex + digits + 1);
                    }
                    double stopLosPre = Double.parseDouble(text);
                    sl = stopLosPre;

                    if (whatBuyRiseOrFall == 0) {
                        if (stopLosPre <= stopLossMax) {
//                            sl = stopLosPre;

                            stopLossTotal = Arith.sub(stopLosPre, stopLossMax);
                            double profit;
                            profit = getMyProfit(sl, 0, pendingPrice);

                            if (profit == -1) return;
                            tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
//                            sl = 0;
                            stopLossTotal = 0;
                            tvLoss.setText("不在范围内");
                        }

                    } else {
                        if (stopLosPre >= stopLossMax) {
//                            sl = stopLosPre;
                            stopLossTotal = Arith.sub(stopLosPre, stopLossMax);
                            double profit;
                            profit = getMyProfit(sl, 1, pendingPrice);

                            if (profit == -1) return;
                            tvLoss.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
//                            sl = 0;
                            stopLossTotal = 0;
                            tvLoss.setText("不在范围内");
                        }
                    }
                    break;
                case 3:
                    if (textLength - dotIndex > digits + 1 && dotIndex != -1) {
                        text = text.substring(0, dotIndex + digits + 1);
                    }
                    double stopProPre = Double.parseDouble(text);
                    tp = stopProPre;
                    if (whatBuyRiseOrFall == 0) {
                        if (stopProPre >= stopProfitMax) {
//                            tp = stopProPre;
                            stopProfitTotal = Arith.sub(stopProPre, stopProfitMax);
                            double profit;
                            profit = getMyProfit(tp, 0, pendingPrice);
                            if (profit == -1) return;
                            tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
//                            tp = 0;
                            stopProfitTotal = 0;
                            tvProfit.setText("不在范围内");
                        }

                    } else {
                        if (stopProPre <= stopProfitMax) {
//                            tp = stopProPre;
                            stopProfitTotal = Arith.sub(stopProPre, stopProfitMax);
                            double profit;
                            profit = getMyProfit(tp, 1, pendingPrice);
                            if (profit == -1) return;
                            tvProfit.setText("预期盈亏：" + BaseUtils.dealSymbol(profit));
                        } else {
//                            tp = 0;
                            stopProfitTotal = 0;
                            tvProfit.setText("不在范围内");
                        }
                    }
                    break;
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private double getMyProfit(double slOrTp, int cmd, double pendingPrice) {
        if (pendingPrice == 0)
            return CountClass.getProfit(slOrTp, cmd, askBidOne, askBidThree, contracSize, volume, profitChange, profitUSDPrex);
        else {
            double[] dd = new double[]{pendingPrice, pendingPrice};
            return CountClass.getProfit(slOrTp, cmd, dd, askBidThree, contracSize, volume, profitChange, profitUSDPrex);
        }
    }

    /**
     * 展示开仓成功后返回信息
     */
    private void setPopupTraderOpenSuccess(OpenTrader openTrader) {
        showTime = 5000;
        View view = View.inflate(getContext(), R.layout.pop_trade_result, null);//pop_style_order_success
        ImageView ivTradeStatus = (ImageView) view.findViewById(R.id.iv_trade_status);
        TextView tvChName = (TextView) view.findViewById(R.id.tv_ch_name);
        TextView tvEnName = (TextView) view.findViewById(R.id.tv_en_name);
        TextView tvValume = (TextView) view.findViewById(R.id.tv_valume);
        TextView tvTradePrice = (TextView) view.findViewById(R.id.tv_trade_price);
        tvChName.setText(openTrader.getSymbolCn());
        tvEnName.setText(openTrader.getSymbol());
        tvValume.setText(openTrader.getVolume() + "手");
        tvTradePrice.setText("开仓价：" + openTrader.getOpenPrice());
        if (openTrader.getCmd() == 0) {
            ivTradeStatus.setImageResource(R.mipmap.buy_icon);
        } else {
            ivTradeStatus.setImageResource(R.mipmap.sell_icon);
        }

        EventBus.getDefault().post(new EventDatas(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE, null));
        isFinishActivity = true;
        showPopupWindow(view);
        runnable = new Runnable() {
            @Override
            public void run() {
                showTime -= 1000;
                if (showTime == 0) {
                    handler.removeCallbacks(runnable);
                    popupWindow.dismiss();
                    getActivity().finish();

                } else
                    handler.postDelayed(runnable, 1000);
            }
        };
        handler.post(runnable);
    }
}
